<?php
namespace App\Admin\Controllers\System;

use App\Admin\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Admin\Models\DictType;
use App\Admin\Models\DictData;
use Illuminate\Database\Query\Builder;

use App\Admin\Admin;
use App\Admin\Actions\DataTable;
use App\Admin\Actions\SoftDelete;
use App\Admin\Actions\Create;
use App\Admin\Actions\Update;
use App\Admin\Actions\Delete;

class DictDataController extends Controller
{
	use DataTable, SoftDelete, Create, Update, Delete;

	public function modelName()
	{
		return DictData::class;
	}

	public function dataTable($setter)
	{
		$setter->validate(function($request){
			return $request->validate([
				'type_id' => 'required|exists:system_dict_type,id',
			]);
		});
		$setter->search(function($query, $validated){
			if( !empty($validated['type_id']) ){
				$query->where('type_id', $validated['type_id']);
			}
		});
	}

	public function storeAndUpdateValidate($request, $model=null)
	{
		if( $model ){
			$unique = Rule::unique(DictData::class)->where(fn (Builder $query) => $query->where('type_id', $model->type_id))->ignore($model->id);
			$rules = [
				'label'   => ['sometimes', 'string', $unique],
				'value'   => ['sometimes', 'string', $unique],
				'sort'    => 'sometimes|integer|min:0',
				'status'  => 'sometimes|integer|boolean',
			];


		}else{
			$type_id = $request->input('type_id');
			$unique = Rule::unique(DictData::class)->where(
				fn (Builder $query) => $query->where('type_id', $type_id)
			);
			$rules = [
				'type_id' => 'required|exists:system_dict_type,id',
				'label'   => ['required', 'string', $unique],
				'value'   => ['required', 'string', $unique],
				'sort'    => 'required|integer|min:0',
				'status'  => 'required|integer|boolean',
			];
		}


		return $request->validate($rules);
	}

	/**
	 * http://www.llc.com/api/admin/system/dict-data/list?code=user_sex
	 */
	public function list(Request $request)
	{
		$code = $request->input('code');
		$expect = $request->input('expect');
		abort_unless($code, 404, '需要参数code');

		$type = DictType::where('code', $code)->first(['id', 'name']);

		$data = [];
		if( $type ){
			$models = DictData::where('type_id', $type->id)->get(['id', 'label', 'value']);

			if( $expect=='int' ){
				$models->each(function ($model) {
				    $model->value = (int) $model->value; // 将 'id' 字段转换为整数
				});
			}
		}

		return Admin::success($models, 0, $type?'success':"请求成功，但是字典:{$code}不存在");
	}
}
